import Vue from 'vue'
import Vuex from 'vuex'
import { getItem, KEY_USER_TOKEN, setItem } from '@/utils/storage'
import comment from './modules/comment'
import addNsname from './add-nsname'

Vue.use(Vuex)

const state = {
  userToken: getItem(KEY_USER_TOKEN)
}

export const getters = {
  // ?. 可选链操作符
  token: state => state.userToken?.token,
  refreshToken: state => state.userToken?.refresh_token
}
addNsname(undefined, getters)

// for (const getter of Object.values(getters)) {
//   getter.nsname = getter.name
// }

export const mutations = {
  changeUserToken (state, newUserToken) {
    state.userToken = newUserToken
    // Vuex 的数据确实变了，但是 localStorage 还没变
    setItem(KEY_USER_TOKEN, newUserToken)
  }
}
addNsname(undefined, mutations)

// for (const mutation of Object.values(mutations)) {
//   mutation.nsname = mutation.name
// }

export const actions = {}
addNsname(undefined, actions)

// for (const action of Object.values(actions)) {
//   action.nsname = action.name
// }

const modules = {
  // 动态从 comment 模块中获取模块名称，绑定到 modules 选项中
  [comment.name]: comment
}

// Vuex 中的数据一旦页面刷新，就重置了
export default new Vuex.Store({
  state,
  getters,
  mutations,
  actions,
  modules
})
